<script lang="ts" setup>
import { ref, watch } from 'vue';
import { MasonryInfiniteGrid } from '@egjs/vue3-infinitegrid';
import { searchApi } from '~/utils/api/search-api';

const route = useRoute();
const keyword = ref((route.query.keyword as string) || '');

const pageNo = 1;
const pageSize = 10;
const { data } = await searchApi.searchArticleServer(keyword.value, pageNo, pageSize);
const articleList = ref(data.value?.data.list || []);
const articleListLength = ref(data.value?.data.total || 0);

watch(() => route.query.keyword, async (newKeyword) => {
	console.log('newKeyword', newKeyword);
	keyword.value = newKeyword as string || '';
	articleList.value = [];
	const result = await searchApi.searchArticle(keyword.value, pageNo, pageSize);
	articleList.value = result.data?.list || [];
	articleListLength.value = result.data?.total || 0;
});

const column = ref(1);

function updateColumn() {
	switch (getScreenSize()) {
		case 'md':
			column.value = 1;
			return;
		case 'lg':
			column.value = 2;
			return;
		case 'xl':
			column.value = 3;
			return;
		case '2xl':
			column.value = 3;
			return;
		default:
			column.value = 1;
			return;
	}
}

onMounted(() => {
	updateColumn();
	window.addEventListener('resize', () => {
		updateColumn();
	});
});
</script>

<template>
	<div class="container">
		<div class="flex flex-col gap-3 my-[6.25rem]">
			<p class="text-center text-5xl font-bold">
				搜索内容: "{{ keyword }}"
			</p>
			<p class="text-center text-xl font-medium ">
				共{{ articleListLength }}篇
			</p>
		</div>
		<ClientOnly>
			<masonry-infinite-grid
				:column="column"
				:gap="10"
				:observe-children="true"
				:use-resize-observer="true"
				class="relative w-full mb-8"
			>
				<div
					v-for="(item, index) in articleList"
					:key="index"
					class="item w-full md:w-[50%] lg:w-[33%]"
				>
					<ArticleCard :article="item" />
				</div>
				<template #placeholder="{ item }">
					<div
						:key="item.key"
						:data-grid-groupkey="item.groupKey"
						class="placeholder"
					/>
				</template>
				<template #loading="{ item }">
					<div
						:key="item.key"
						:data-grid-groupkey="item.groupKey"
						class="loading"
					>
						加载中……
					</div>
				</template>
			</masonry-infinite-grid>
		</ClientOnly>
	</div>
</template>

<style scoped>

</style>
